package com.mm.service.impl;

import com.mm.service.SendMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class SendMailImpl implements SendMailService {

    private final JavaMailSender mailSender;

    private final static Logger logger = LoggerFactory.getLogger(SendMailImpl.class);

    @Value("${spring.mail.username}")
    private String fromEmail;

    public SendMailImpl(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Override
    public boolean sendMailToText(String toEmail, String subject, String text) {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom(fromEmail);
        msg.setTo(toEmail);
        msg.setSubject(subject);
        msg.setText(text);
        try {
            mailSender.send(msg);
        } catch (MailException ex) {
            logger.error("邮件发送失败");
            logger.error(ex.getMessage());
            return false;
        }
        logger.info("以向【" + toEmail + "】发送邮件，内容：" + text);
        return true;
    }

}
